<template>
  <el-dialog :title="roleId ? '编辑角色' : '添加角色'" :visible.sync="dialogFormVisible">
    <el-form :model="form" ref="form">
      <el-form-item label="角色名称" :label-width="formLabelWidth" prop="name">
        <el-input v-model="form.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="角色编码" :label-width="formLabelWidth" prop="code">
        <el-input v-model="form.code" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" :label-width="formLabelWidth" prop="description">
        <el-input v-model="form.description" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { getRoleById, saveOrUpdate } from '@/services/role'

  export default {
    name: 'CreateOrEdit',
    props: {
      dialogFormVisible: {
        type: Boolean,
        required: true,
      },
      roleId: {
        type: Number,
      }
    },
    data() {
      return {
        formLabelWidth: '120px',
        form: {
          name: '',
          code: '',
          description: '',
        },
      }
    },
    methods: {
      cancel() {
        this.$refs.form.resetFields()
        this.$emit('close')
      },
      async onSubmit() {
        const { code } = await saveOrUpdate(this.form)
        if (code === '000000') {
          this.roleId ? this.$message.success('修改成功') : this.$message.success('添加成功')
        }
        this.$refs.form.resetFields()
        this.$emit('success')
      },
      async loadRoleData(roleId) {
        const { code, data } = await getRoleById(roleId)
        if (code === '000000') {
          this.form = data
        }
      }
    },
    watch: {
      roleId(newValue) {
        console.log('roleId>>', newValue)
        if (newValue) {
          this.loadRoleData(newValue)
        }
      }
    }
  }
</script>
